package io.invertase.firebase.messaging;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import com.facebook.react.HeadlessJsTaskService;
import com.google.firebase.messaging.RemoteMessage;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.invertase.firebase.common.ReactNativeFirebaseEventEmitter;
import io.invertase.firebase.common.SharedUtils;

public class ReactNativeFirebaseMessagingReceiver extends BroadcastReceiver {
  private static final String TAG = "RNFirebaseMsgReceiver";
  private final String FCM_NOTIFICATION = "fcm_notification";
  static HashMap<String, RemoteMessage> notifications = new HashMap<>();
  private Context mContext;

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "broadcast received for message");
    mContext = context.getApplicationContext();

    RemoteMessage remoteMessage = new RemoteMessage(intent.getExtras());
    ReactNativeFirebaseEventEmitter emitter = ReactNativeFirebaseEventEmitter.getSharedInstance();

    //  |-> ---------------------
    //      App in Foreground
    //   ------------------------
    if (SharedUtils.isAppInForeground(context)) {
      emitter.sendEvent(ReactNativeFirebaseMessagingSerializer.remoteMessageToEvent(remoteMessage, false));
      Map<String, String> data = remoteMessage.getData();
      JSONObject jsonObj = new JSONObject(data);
      sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(),  jsonObj.toString(),false, remoteMessage.getMessageId());
      if (remoteMessage.getNotification() != null) {
        notifications.put(remoteMessage.getMessageId(), remoteMessage);
      }
      return;
    }


    //  |-> ---------------------
    //    App in Background/Quit
    //   ------------------------

    // Add a RemoteMessage if the message contains a notification payload
    if (remoteMessage.getNotification() != null) {
      notifications.put(remoteMessage.getMessageId(), remoteMessage);
    }

    try {
      Intent backgroundIntent = new Intent(context, ReactNativeFirebaseMessagingHeadlessService.class);
      backgroundIntent.putExtra("message", remoteMessage);
      ComponentName name = context.startService(backgroundIntent);
      if (name != null) {
        HeadlessJsTaskService.acquireWakeLockNow(context);
      }
    } catch (IllegalStateException ex) {
      // By default, data only messages are "default" priority and cannot trigger Headless tasks
      Log.e(
        TAG,
        "Background messages only work if the message priority is set to 'high'",
        ex
      );
    }
  }

  public void sendNotification(String messageTitle, String messageBody, String hiddendata, boolean isBigText, String messageID) {
    //如果没有自定义intent跳转就采用默认的跳转
    Class cl = null;
      try {
        cl = Class.forName("com.menu_rn.MainActivity");
      } catch (ClassNotFoundException e) {
       Log.e("hellw", "ClassNotFoundException e = "+e.getMessage());
    }
      Intent openIntent = new Intent(mContext, cl);
      openIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      Bundle bundle = new Bundle();
      bundle.putString("message_id", messageID);
      openIntent.putExtras(bundle);
      openIntent.putExtra("hiddendata", hiddendata);
      openIntent.putExtra("data", hiddendata);


    PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, openIntent,
      PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    //适配Android O
    String channelId = "12345";
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
      CharSequence name = "VeSync";
      String Description = "This is my channel";
      int importance = NotificationManager.IMPORTANCE_DEFAULT;
      NotificationChannel mChannel = new NotificationChannel(channelId, name, importance);
      mChannel.setDescription(Description);
      mChannel.enableLights(true);
      mChannel.setLightColor(Color.RED);
      mChannel.enableVibration(true);
      mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
      mChannel.setShowBadge(false);
      notificationManager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder notificationBuilder;
    //判断是否使用大文本样式
    if (isBigText){
      notificationBuilder = new NotificationCompat.Builder(mContext, channelId)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(messageTitle)
        .setContentText(messageBody)
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);
      //创建大文本样式
      NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
      bigTextStyle.setBigContentTitle(messageTitle)
        .bigText(messageBody);
      notificationBuilder.setStyle(bigTextStyle); //设置大文本样式
    }else {
      notificationBuilder = new NotificationCompat.Builder(mContext, channelId)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(messageTitle)
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent);
    }
    notificationManager.notify(FCM_NOTIFICATION, 0, notificationBuilder.build());
  }
}

